﻿using StationDataHub.Services;

namespace StationDataHub.TimeJob;

/// <summary>
/// 6.4 设备接口状态查询
/// </summary>
public class QueryConnectorStatusJob(
    IFlurlClientCache client,
    IEasyCachingProvider cache,
    IDbService dbService) : IJob
{
    private readonly IFlurlClient _client = client.Get("ChargePlatform");
    private readonly IEasyCachingProvider _cache = cache;
    private readonly IDbService _db = dbService;

    // 每次请求最多50个stationId
    private const int MaxStationIdsPerRequest = 50;

    public async Task Execute(IJobExecutionContext context)
    {
        try
        {
            var cfg = AppSettings.ChargePlatform.SecurityConfig;
            var api = AppSettings.ChargePlatform.API.Interfaces;

            // 读取缓存 token
            var tokenCache = await _cache.GetAsync<string>("ChargePlatformToken");
            if (!tokenCache.HasValue || string.IsNullOrWhiteSpace(tokenCache.Value))
            {
                Log.Error("[查询充电接口状态] Token 不存在或已过期，跳过任务");
                return;
            }
            // 查询数据库中所有站点 ID
            var stationIds = await _db.GetStationIDsAsync();
            if (stationIds == null || stationIds.Length == 0)
            {
                Log.Information("[查询充电接口状态] 暂无站点数据");
                return;
            }
            // 分批请求，每批最多50个站点ID
            int pageNo = 0;  // 起始页
            int totalPages = (int)Math.Ceiling(stationIds.Length / (double)MaxStationIdsPerRequest);  // 计算总页数

            // 使用 while 循环处理每一批数据
            while (pageNo < totalPages)
            {
                // 获取当前批次的 stationIds（每批最多 50 个）
                var currentBatch = stationIds.Skip(pageNo * MaxStationIdsPerRequest)
                                              .Take(MaxStationIdsPerRequest)
                                              .ToArray();
                // 构造请求体
                var reqBody = new
                {
                    StationIDs = currentBatch
                }.BuildEncryptedRequest();
                // 请求接口
                var respStr = await _client.Request(api.QueryConnectorStatus)
                    .WithHeader("Authorization", $"Bearer {tokenCache.Value}")
                    .PostJsonAsync(reqBody)
                    .ReceiveString();
                var resp = JsonSerializer.Deserialize<APIResponse>(respStr);
                if (resp == null || resp.Ret != 0 || string.IsNullOrEmpty(resp.Data))
                {
                    Log.Error($"[查询充电接口状态] 站点查询失败：{resp?.Msg}");
                    break;  // 如果请求失败，跳出循环
                }
                // 解密数据
                var decrypted = resp.Data.DecryptAES(cfg.AesEncryptionKey, cfg.AesInitialVector);
                var statusResp = JsonSerializer.Deserialize<QueryConnectorStatusResponse>(decrypted);
                if (statusResp != null)
                {
                    var ok = await _db.UpdateConnectorStatusAsync(statusResp);
                    Log.Information($"[查询充电接口状态] {(ok ? "接口状态更新成功" : "无可更新记录")}");
                }
                // 继续请求下一批
                pageNo++;
            }
            //// 构造请求体
            //var reqBody = new
            //{
            //    StationIDs = stationIds
            //}.BuildEncryptedRequest();
            //// 请求
            //var respStr = await _client.Request(api.QueryConnectorStatus)
            //    .WithHeader("Authorization", $"Bearer {tokenCache.Value}")
            //    .PostJsonAsync(reqBody)
            //    .ReceiveString();
            //var resp = JsonSerializer.Deserialize<APIResponse>(respStr);
            //if (resp == null || resp.Ret != 0 || string.IsNullOrEmpty(resp.Data))
            //{
            //    Log.Error($"[查询充电接口状态] 站点查询失败：{resp?.Msg}");
            //    return;
            //}
            //// 解密数据
            //var decrypted = resp.Data.DecryptAES(cfg.AesEncryptionKey, cfg.AesInitialVector);
            //var statusResp = JsonSerializer.Deserialize<QueryConnectorStatusResponse>(decrypted);
            //if (statusResp != null)
            //{
            //    var ok = await _db.UpdateConnectorStatusAsync(statusResp);
            //    Log.Information($"[查询充电接口状态] {(ok ? "接口状态更新成功" : "无可更新记录")}");
            //}
        }
        catch (Exception ex)
        {
            Log.Error(ex, $"[查询充电接口状态] 异常：{ex.Message}");
        }
    }
}